package com.app.yc.ifapp;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.app.yc.ifapp.asynctask.WebApiRequest;
import com.app.yc.ifapp.entity.ApiResult;
import com.app.yc.ifapp.entity.UserInfo;
import com.app.yc.ifapp.utils.ApiUtils;
import com.app.yc.ifapp.utils.EncryptUtils;
import com.app.yc.ifapp.utils.StringUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.net.URLEncoder;

public class LoginActivity extends AppCompatActivity {

    //按住和松开的标识
    int touch_flag = 0;
    String url;
    String pwd;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        //初始化
        initStyles();
    }

    private void initStyles() {
        //获取并缩放右箭头
        Drawable drawable = ContextCompat.getDrawable(this, R.mipmap.right_arrow);
        drawable.setBounds(0, 0, drawable.getIntrinsicWidth() / 4,
                drawable.getIntrinsicHeight() / 4);
        //获取到控件
        EditText et = (EditText)findViewById(R.id.text_login_school);
        //设置右箭头
        et.setCompoundDrawables(null, null, drawable, null);
        //设置OnTouch事件
        et.setOnTouchListener(new EditText.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                touch_flag ++;
                if(touch_flag == 5){
                    Intent intent = new Intent();
                    intent.setClass(LoginActivity.this, SchoolActivity.class);
                    startActivityForResult(intent, 0);
                }
                return false;
            }
        });

        if (TextUtils.isEmpty(et.getText())) {
            Button btn = (Button)findViewById(R.id.button_login_submit);
            btn.setEnabled(false);
        }
    }

    @Override
    /*
      当跳转的activity(被激活的activity)使用完毕,销毁的时候调用该方法
     */
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        touch_flag = 0;
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null) {
            String name = data.getStringExtra("school");

            if (!TextUtils.isEmpty(name)) {
                //获取到控件
                EditText et = (EditText) findViewById(R.id.text_login_school);
                et.setText(name);

                String url = data.getStringExtra("url");
                if (!TextUtils.isEmpty(url)) {
                    //Toast.makeText(this, url, Toast.LENGTH_SHORT).show();
                    Button btn = (Button) findViewById(R.id.button_login_submit);
                    btn.setTag(url);
                    btn.setEnabled(true);
                    //登录按钮点击
                    btn.setOnClickListener(loginOnClick);
                }
            }
        }
    }

    /**
     * 登录按钮点击
     */
    private View.OnClickListener loginOnClick = new  View.OnClickListener() {
        @Override
        public void onClick(View view) {
            view.setEnabled(false);
            WebApiRequest request = new WebApiRequest();
            request.setAsyncTaskCallBack(new WebApiRequest.AsyncTaskCallBack() {
                @Override
                public void onTaskOver(String result) {

                    if (TextUtils.isEmpty(result)) {
                        Toast.makeText(LoginActivity.this, R.string.error_api_fail,
                                Toast.LENGTH_SHORT).show();
                        return;
                    }

                    try {
                        Gson gson = new Gson();
                        ApiResult<UserInfo> apiResult = gson.fromJson(result,
                                new TypeToken<ApiResult<UserInfo>>() {}.getType());

                        if (apiResult == null) {
                            Toast.makeText(LoginActivity.this,
                                    R.string.error_api_fail,
                                    Toast.LENGTH_SHORT).show();
                            return;
                        }

                        if (apiResult.getResult() && apiResult.getData() != null) {
                            //保存登录信息
                            SharedPreferences sp = getSharedPreferences("login_user",
                                    Context.MODE_PRIVATE);
                            SharedPreferences.Editor editor = sp.edit();
                            editor.putString("user_no", apiResult.getData().getUserNo());
                            editor.putString("password", pwd);
                            editor.putString("url", url);
                            editor.apply();

                            Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                            //把附加的数据放到意图当中
                            intent.putExtra("user", apiResult.getData());
                            intent.putExtra("url", url);
                            LoginActivity.this.startActivity(intent);
                            finish();
                        } else {
                            Toast.makeText(LoginActivity.this, apiResult.getMessage(),
                                    Toast.LENGTH_SHORT).show();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    finally {
                        findViewById(R.id.button_login_submit).setEnabled(true);
                    }
                }
            });

            try {
                EditText et_user = (EditText)findViewById(R.id.text_login_user);
                EditText et_password = (EditText)findViewById(R.id.text_login_password);

                String user = et_user.getText().toString();
                String password = et_password.getText().toString();

                //验证是否输入了用户名与密码
                if (TextUtils.isEmpty(user) ||
                        TextUtils.isEmpty(password)) {
                    Toast.makeText(LoginActivity.this, R.string.error_login_input,
                            Toast.LENGTH_SHORT).show();
                    return;
                }

                url = view.getTag().toString();
                pwd = password;
                //构造请求登录参数
                String params = "?empStrId" + "=" +
                        URLEncoder.encode(user, "UTF-8") +
                        "&userPwd" + "=" +
                        URLEncoder.encode(EncryptUtils.SHA.SHA256(password), "UTF-8");

                request.execute(url + ApiUtils.LOGIN + params,
                        StringUtils.EMPTY);
            } catch (Exception e) {
                e.printStackTrace();
                Toast.makeText(LoginActivity.this, R.string.error_api_fail,
                        Toast.LENGTH_SHORT).show();
            }
        }
    };
}
